import router from "@/utils/router";
import NProgress from "nprogress";
import { useUserStore } from '@/utils/stores/modules/user'
import { PageEnum } from '@/utils/enums/pageEnums'
import { INDEX_ROUTE_NAME, INDEX_ROUTE } from '@/utils/router/routes'
import { isExternal } from '@/utils/common'
import { findFirstValidRoute } from '@/utils/router'
import { markRaw } from 'vue'
import type { RouteRecordRaw } from 'vue-router'

// 登录页面
const loginPath = PageEnum.LOGIN
// 首页
const defaultPath = PageEnum.HOME

// 白名单
const whiteList: string[] = [loginPath]

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {

    // 开始 Progress Bar
    NProgress.start()
    const userStore = useUserStore()
    if (whiteList.includes(to.path)) {
        // 在免登录白名单，直接进入
        next()
    } else if (userStore.token) {
        // 获取用户信息
        const hasGetUserInfo = Object.keys(userStore.userInfo).length !== 0
        if (hasGetUserInfo) {
            if (to.path === loginPath) {
                next({ path: defaultPath })
            } else {
                next()
            }
        } else {
            try {
                await userStore.getUserInfo()
                const routes = userStore.routes
                // 找到第一个有效路由
                const routeName = findFirstValidRoute(routes)
                if (!routeName) {
                    next({ path: '/403' })
                    return
                }

                // 添加 index 路由
                const indexRoute: RouteRecordRaw = {
                    ...INDEX_ROUTE,
                    redirect: { name: routeName },
                    children: []  // 添加空的子路由数组
                }
                router.addRoute(indexRoute)

                // 处理子路由
                routes.forEach((route: any) => {
                    if (isExternal(route.path)) {
                        return
                    }
                    
                    if (!route.children) {
                        const singleRoute: RouteRecordRaw = {
                            ...route,
                            component: markRaw(route.component)
                        }
                        router.addRoute(INDEX_ROUTE_NAME, singleRoute)
                        return
                    }
                    
                    const parentRoute: RouteRecordRaw = {
                        ...route,
                        component: markRaw(route.component),
                        children: route.children.map((child: any) => ({
                            ...child,
                            component: markRaw(child.component)
                        }))
                    }
                    router.addRoute(parentRoute)
                })
                next({ ...to, replace: true })
            } catch (err) {
                next({ path: loginPath, query: { redirect: to.fullPath } })
            }
        }
    } else {
        next({ path: loginPath, query: { redirect: to.fullPath } })
    }
})


router.afterEach((to) => {

    NProgress.done()
})

